<template>
  <WebHeader />
  <div class="sqcontent contentwidth">
    <div class="header">
      <table>
        <thead>
          <tr>
            <th colspan="2">征求意见详情</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>项目编号</td>
            <td>{{tableData.projectNumber}}</td>
          </tr>
          <tr>
            <td>项目名称</td>
            <td>{{tableData.standardProjectName}}</td>
          </tr>
          <tr>
            <td>截止日期</td>
            <td>{{tableData.solicitOpinionsDeadline}}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="main-content">
      <h3>征求意见函</h3>
      <div v-html="tableData.solicitOpinionsComment"></div>
      <div class="links">
        <a href="#"
           @click.prevent="downloadFile(tableData.solicitOpinionsFile)">征求意见稿</a>
        <br />
        <a href="#"
           @click.prevent="downloadFile(tableData.opinionFillTemplate)">意见表</a>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive, onMounted } from "vue";
  import { ElConfigProvider, ElMessage } from "element-plus";
  import zhCn from "element-plus/es/locale/lang/zh-cn";
  import axios from "axios";
  import { useRoute } from "vue-router";
  import WebHeader from "@/components/header/index.vue";
  import CryptoJS from "crypto-js";
    import { getServerUrl } from "@/utils/url";
  const serverUrl = getServerUrl();
  const route = useRoute();

  const tableData = ref([]);
  const showDetail = (value: any) => {
    // window.open(fileUrl.value, '_blank'); // 使用_blank在新窗口中打开
  };

  const initData = async (id: any) => {
    try {
      const response = await axios.get(
        serverUrl + `external/standard/draft/${id}`
      );
      console.log(response, "res");
      tableData.value = response.data.data;
    } catch (error) {
      console.error("数据加载失败:", error);
    }
  };
  onMounted(() => {
    const id = route.query.id as string;
    initData(id);
  });
  const downloadFile = async (value: any) => {
    if (value.id) {
      const timestamp = Date.now();
      const secretKey = "jkysh2jgbstandard";
      // 生成receivedToken
      const receivedToken = CryptoJS.HmacSHA256(
        value.id + ":" + timestamp,
        secretKey
      ).toString(CryptoJS.enc.Hex);
      try {
        const response = await axios.get(
          serverUrl + "api/files/webDownload",
          {
            params: {
              // 修正：GET 请求参数应放在 `params` 中
              fileId: value.id,
              timestamp: timestamp,
              receivedToken: receivedToken,
            },

            responseType: "blob",
          }
        );

        // 从响应头中提取文件名和文件类型

        const contentDisposition =
          response.headers["content-disposition"] ||
          response.headers["Content-Disposition"];
        const contentType = response.headers["content-type"];

        // 默认文件名和文件类型
        let fileName =
          getFileNameFromContentDisposition(contentDisposition) ||
          "default-filename";
        let fileExtension = "bin"; // 默认扩展名

        // 提取文件名
        // if (contentDisposition) {
        //     const match = contentDisposition.match(/filename="?(.+)"?/);
        //     if (match && match[1]) {
        //         fileName = match[1];
        //     }
        // }

        // 提取文件扩展名（根据 Content-Type）
        if (contentType) {
          const extensionMap: Record<string, string> = {
            "application/pdf": "pdf",
            "application/msword": "doc",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
              "docx",
            "application/vnd.ms-excel": "xls",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
              "xlsx",
            "image/jpeg": "jpg",
            "image/png": "png",
            "text/plain": "txt",
          };
          fileExtension = extensionMap[contentType] || fileExtension;
        }

        // 确保文件名包含正确的扩展名
        if (!fileName.includes(".")) {
          fileName = `${fileName}.${fileExtension}`;
        }

        // 创建 Blob 对象并生成下载链接
        const blob = new Blob([response.data]);
        const downloadUrl = window.URL.createObjectURL(blob);

        // 创建 <a> 标签并触发下载
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = fileName; // 使用动态生成的文件名
        document.body.appendChild(a);
        a.click();

        // 清理资源
        document.body.removeChild(a);
        window.URL.revokeObjectURL(downloadUrl);
      } catch (error) {
        console.error("文件下载失败：", error);
      }
    } else {
      ElMessage.error("暂无文件");
    }
  };
  const getFileNameFromContentDisposition = (contentDisposition: string) => {
    if (!contentDisposition) return null;

    // 处理标准文件名（filename="..."）
    const filenameMatch = contentDisposition.match(/filename="?(.+?)"?(;|$)/i);
    if (filenameMatch && filenameMatch[1]) {
      return decodeURIComponent(filenameMatch[1]); // 解码 URL 编码
    }

    // 处理 RFC 5987 编码的文件名（filename*=UTF-8''...）
    const filenameStarMatch = contentDisposition.match(
      /filename\*=UTF-8''(.+?)(;|$)/i
    );
    if (filenameStarMatch && filenameStarMatch[1]) {
      return decodeURIComponent(filenameStarMatch[1]); // 解码 URL 编码
    }

    return null; // 未找到文件名
  };
</script>
<style lang="scss" scoped>
.sqcontent {
  margin: 20px auto 80px;
  border: 1px solid #e9eaec;
  border-color: #e9eaec;
  border-radius: 4px;
  padding: 16px;
  box-sizing: border-box;
}

.header {
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #cccccc61;
  padding: 8px;
  text-align: center;
}

th {
  background: #599beb;
  color: #fff;
  font-weight: 700;
}

td {
  color: #606266;
}

.main-content {
  line-height: 1.6;
}

h2,
h3 {
  margin: 10px 0;
}

.signature {
  text-align: right;
  margin-top: 20px;
}

.signature-date {
  text-align: right;
}

.links {
  margin-top: 20px;
}

a {
  color: #0066cc;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>